package com.digitalchina.lxnsy.zbsy;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.handheld.UHFLonger.UHFLongerManager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class TagManageScanActivity extends BaseActivity {

    private UHFLongerManager manager = null;
    public SoundPool sp;
    public Map<Integer, Integer> suondMap;
    private boolean runFlag = true;
    private boolean startFlag = false;

    private Thread thread, threadConnect;

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_tag_manage_scan);
        setTitle("扫描耳标");
    }

    @Override
    public void initMember() {
        showToast("正在加载模块...");
        runFlag = true;

        initSoundPool(activity);

        //扫描线程
        thread = new InventoryThread();
        thread.start();

        //初始化线程
        threadConnect = new ConnectThread();
        threadConnect.start();

//        if (manager != null)
//            manager.clearSelect();

    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                return false;
            }
        });
    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {

    }


    @Override
    protected void onDestroy() {
        thread.interrupt();
        startFlag = false;
        runFlag = false;
//        if (manager != null) {
//            manager.close();
//            manager = null;
//        }
        super.onDestroy();
    }

    private void connect() {
        try {
            if (manager == null)
                manager = UHFLongerManager.getInstance();

            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    SharedPreferences shared = getSharedPreferences("settings", 0);
                    final int value = shared.getInt("power", 30);
                    if (manager != null) {
                        if (manager.setOutPower((short) value)) {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    //showToast(getString(R.string._power_now) + value);
                                }
                            });
                        }
                        final int reg = shared.getInt("freband", 1);
                        if (manager.setFreBand((short) reg)) {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    //showToast(getString(R.string._freBand) + getResources().getStringArray(R.array.freBandArray)[reg]);
                                }
                            });
                        }
                    }
                }
            }, 1000);
        } catch (Exception e) {

            e.printStackTrace();
        }

        if (manager == null) {
            Looper.prepare();
            if (activity != null && !activity.isFinishing()) {
         //       showToast("串口初始化失败");
                CustomDialog.nativeDialogFinish(activity, "初始化失败，当前设备不支持扫描！");
            }
            Looper.loop();
            return;
        } else {
            startFlag = true;
            play(1, 0);
            Looper.prepare();
            if (activity != null && !activity.isFinishing())
           //     showToast("初始化成功");
            Looper.loop();
        }

    }


    //init sound pool
    public void initSoundPool(Context context) {

        sp = new SoundPool(1, AudioManager.STREAM_MUSIC, 1);
        suondMap = new HashMap<>();
        suondMap.put(1, sp.load(context, R.raw.msg, 1));
    }

    //play sound
    public void play(int sound, int number) {
        AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
        //return AlarmManager The largest volume at present
        float audioMaxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

        //return AlarmManager The largest volume at present
        float audioCurrentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        float volumnRatio = audioCurrentVolume / audioMaxVolume;
        sp.play(
                suondMap.get(sound), //get sound id
                audioCurrentVolume, //left volume
                audioCurrentVolume, //ringht volume
                1, //priority
                number, //cycles
                1);//0.5-2.0 speed
    }

    //循环取值
    class InventoryThread extends Thread {
        private List<String> epcList;

        @Override
        public void run() {
            super.run();
            while (runFlag) {

                if (thread.isInterrupted()) {
                    break;
                }

                if (startFlag) {
                    epcList = manager.inventoryRealTime(); //
                    if (epcList != null && !epcList.isEmpty()) {
                        play(1, 0);
                        startFlag = false;
                        Intent intent = new Intent();
                        intent.putExtra("chipNo", epcList.get(0));
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                    epcList = null;
                }
            }
        }
    }

    class ConnectThread extends Thread {
        @Override
        public void run() {
            connect();
        }
    }
}
